/* 
 * Copyright (c)	Insighten Intelligent Equipment co.,LTD
 * 
 *  Use of this software is controlled by the terms and conditions found
 *  in the license agreement under which this software has been supplied.
 * 
 */
/** 
 * @file tcp_server.h
 * @brief library for tcp server
 * @author taco [tacoee@gmail.com]
 * @version 0.1
 * @date 2010-09-03
 */

#ifndef TCP_SERVER_H_
#define TCP_SERVER_H_

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>

#include "rwbuf.h"
#include "sock_util.h"
#include "types.h"

#define COMMAND_LEN		64
#define COMVAL_LEN		64

struct _TcpServer;
typedef struct _TcpServer TcpServer;
struct _TcpServer {
	int fd;
	int port;
	struct sockaddr_in addr;
	socklen_t addr_len;
	int max_con;	/*max connection*/
	int con_cnt;	/*total connections*/
	SocketAttr *attr;
};

typedef enum _Method {
	M_POST,
	M_GET,
	M_NO
} Method;

typedef struct _Command {
	char cmd_name[COMMAND_LEN];
	char cmd_val[COMVAL_LEN];
	struct _Command *prev;
	struct _Command *next;
} Command;

struct _Request;
typedef struct _Request Request;

struct _Request {
	Request *next;
	Request *prev;
	int fd;
	struct sockaddr cliaddr;
	int clilen;
	SocketAttr *attr;
	SockStat status;
	RwBuf		*buf;
	Command		*cmd;
	Method	method;
	int context_lenght;
	int parse_pos;
	char *cmd_end_pos;
};

TcpServer *tcp_server_new(void);
Ret tcp_server_destroy(TcpServer *thiz);
Ret tcp_server_init(TcpServer *thiz, int port, int max, SocketAttr *attr);
Ret tcp_server_create(TcpServer *thiz);
Request *request_new();
void request_enqueue(Request **head, Request *req);
void request_dequeue(Request **head, Request *req);
Ret request_free(Request *thiz);
Request *tcp_server_request(TcpServer *thiz, SocketAttr *cli_attr);
Ret tcp_server_dis_client(Request *thiz, TcpServer *svr);
int tcp_server_read(Request *req, int size);
int tcp_server_write(Request *req, int size);
Ret tcp_server_req_buf_init(Request *thiz, RwBuf *buf);

Command *command_new();
Ret command_destory(Command *thiz);
#endif
